package net.zoneland.zrdp.system.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.validation.ValidationException;
import javax.validation.Validator;

import lombok.Data;
import net.zoneland.zrdp.common.core.redis.RedisService;
import net.zoneland.zrdp.common.utils.spring.SpringUtils;
import net.zoneland.zrdp.system.service.mapstruct.BaseInfoConverter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections4.CollectionUtils;

import net.zoneland.zrdp.common.annotation.DataScope;
import net.zoneland.zrdp.common.core.domain.entity.SysRole;
import net.zoneland.zrdp.common.core.domain.entity.SysUser;
import net.zoneland.zrdp.common.exception.ServiceException;
import net.zoneland.zrdp.common.utils.SecurityUtils;
import net.zoneland.zrdp.common.utils.bean.BeanValidators;
import net.zoneland.zrdp.system.domain.SysPost;
import net.zoneland.zrdp.system.domain.SysUserPost;
import net.zoneland.zrdp.system.domain.SysUserRole;
import net.zoneland.zrdp.system.mapper.SysPostMapper;
import net.zoneland.zrdp.system.mapper.SysRoleMapper;
import net.zoneland.zrdp.system.mapper.SysUserMapper;
import net.zoneland.zrdp.system.mapper.SysUserPostMapper;
import net.zoneland.zrdp.system.mapper.SysUserRoleMapper;
import net.zoneland.zrdp.system.service.ISysConfigService;
import net.zoneland.zrdp.system.service.ISysUserService;

import static net.zoneland.zrdp.common.constant.Constants.FILE_DOWNLOAD_KEY;

/**
 * 用户 业务层处理
 *
 * @author zonevue
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysUserPostMapper userPostMapper;

    @Resource
    private ISysConfigService configService;

    @Resource
    protected Validator validator;

    @Resource
    private RedisService redisService;

    private static final int EXPIRATION_TIME = 30;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(final SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(final SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(final SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(final String userName) {
        return userMapper.selectUserByUserName(userName);
    }
    /**
     * 复制一份user对象，新用户对象不返回password，并且生成用户头像访问的token
     *
     * @param user 用户
     * @return 用户对象信息不返回password
     */
    @Override
    public SysUser removePassword(SysUser user) {
        // 给图片访问生成认证需要的token
        final String uuid = UUID.randomUUID().toString();
        redisService.setCacheString(FILE_DOWNLOAD_KEY + uuid, "true", EXPIRATION_TIME, TimeUnit.MINUTES);
        final SysUser sysUser = BaseInfoConverter.INSTANCE.userToSysUser(user);
        sysUser.setVisitToken(uuid);
        sysUser.setPassword(null);
        return sysUser;
    }
    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(final Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(final String userName) {
        final List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(final String userName) {
        final List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(final SysUser user) {
        final long userId = Objects.isNull(user.getUserId()) ? -1L : user.getUserId();
        final SysUser info = userMapper.selectOneByUserName(user.getUserName());
        return Objects.isNull(info) || info.getUserId() == userId;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return 是否唯一
     */
    @Override
    public boolean checkPhoneUnique(final SysUser user) {
        final long userId = Objects.isNull(user.getUserId()) ? -1L : user.getUserId();
        final SysUser info = userMapper.selectOneByPhone(user.getPhoneNumber());
        return Objects.isNull(info) || info.getUserId() == userId;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return 是否唯一
     */
    @Override
    public boolean checkEmailUnique(final SysUser user) {
        final long userId = Objects.isNull(user.getUserId()) ? -1L : user.getUserId();
        final SysUser info = userMapper.selectOneByEmail(user.getEmail());
        return Objects.isNull(info) || info.getUserId() == userId;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 需要被操作的用户信息
     */
    @Override
    public void checkUserAllowed(final SysUser user) {
        if (Objects.nonNull(user.getUserId()) && user.isAdmin() && !SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(final Long userId) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            final SysUser user = new SysUser();
            user.setUserId(userId);
            // 这里需要用到 selectUserList 方法上面的aop 注解，用来判断是否有访问用户的数据权限
            final List<SysUser> users = SpringUtils.getAopProxy((ISysUserService)this).selectUserList(user);
            if (CollectionUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息（包含基础信息，角色信息，岗位信息）
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(final SysUser user) {
        // 新增用户信息
        final int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(final SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息（包含基础信息，角色信息，岗位信息）
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(final SysUser user) {
        final Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 只更新用户基本信息，不更新岗位和角色
     * @param user 用户信息
     * @return 影响行数
     */
    @Override
    public int updateUserOnly(final SysUser user) {
        return userMapper.updateUser(user);
    }
    /**
     * 用户授权角色
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(final Long userId, final Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(final SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(final SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(final String userName, final String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(final SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(final String userName, final String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(final SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    private void insertUserPost(final SysUser user) {
        final Long[] posts = user.getPostIds();
        if (ArrayUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            final List<SysUserPost> list = Arrays.stream(posts).map(postId -> {
                final SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                return up;
            }).collect(Collectors.toList());

            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    private void insertUserRole(final Long userId, final Long[] roleIds) {
        if (ArrayUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            final List<SysUserRole> list = Arrays.stream(roleIds).map(roleId -> {
                final SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                return ur;
            }).collect(Collectors.toList());
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(final Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(final Long[] userIds) {
        for (final Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据，不需要事务，成功一条数据库就记录一条
     * 因为业务需要单条进行导入或者更新，并且记录单条的执行结果，不能因为其中一条失败就导致全部失败（收集出错的条目），因此不开启事务。因此抑制 sonar(java:S2229)
     * @param users 用户数据列表
     * @param updateEnabled 是否更新支持，如果已存在，则进行更新数据
     * @param operatorName 操作用户
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    @SuppressWarnings("java:S2229")
    public String importUser(final List<SysUser> users, final boolean updateEnabled, final String operatorName) {
        if (CollectionUtils.isEmpty(users)) {
            throw new ServiceException("导入用户数据不能为空！");
        }

        final String defaultPassword = configService.selectConfigByKey("sys.user.initPassword");

        final List<UserImportResult> results = users.stream()
            .map(user -> importOrUpdateUser(user, updateEnabled, operatorName, defaultPassword))
            .collect(Collectors.toList());

        final Map<Boolean, List<UserImportResult>> partitionedResults = results.stream()
            .collect(Collectors.partitioningBy(UserImportResult::isSuccess));

        final String successMessages = partitionedResults.get(true).stream()
            .map(result -> String.format("<br/>%d、账号 %s 导入成功", result.getIndex(), result.getUser().getUserName()))
            .collect(Collectors.joining());

        final String failureMessages = partitionedResults.get(false).stream()
            .map(result -> String.format("<br/>%d、账号 %s 导入失败：%s", result.getIndex(), result.getUser().getUserName(), result.getError()))
            .collect(Collectors.joining());

        if (results.stream().anyMatch(result -> !result.isSuccess())) {
            throw new ServiceException("很抱歉，导入失败！<br/>" + failureMessages);
        }

        return "恭喜您，数据已全部导入成功！<br/>" + successMessages;
    }

    private UserImportResult importOrUpdateUser(final SysUser user, final boolean updateEnabled,
                                                final String operatorName, final String defaultPassword) {
        try {
            final SysUser existingUser = userMapper.selectUserByUserName(user.getUserName());
            if (Objects.isNull(existingUser)) {
                validateUser(user);
                user.setPassword(SecurityUtils.encryptPassword(defaultPassword));
                user.setCreateBy(operatorName);
                SpringUtils.getBean(ISysUserService.class).insertUser(user); // 这里不需要事务，失败不需要回滚
                return UserImportResult.success(user);
            } else if (updateEnabled) {
                validateUser(user);
                checkUserAllowed(user);
                checkUserDataScope(user.getUserId());
                user.setUserId(existingUser.getUserId());
                user.setUpdateBy(operatorName);
                SpringUtils.getBean(ISysUserService.class).updateUser(user); // 这里不需要事务，失败不需要回滚
                return UserImportResult.success(user);
            } else {
                return UserImportResult.failure(user, "账号已存在");
            }
        } catch (final Exception e) {
            LOGGER.error("User import failed: ", e);
            return UserImportResult.failure(user, e.getMessage());
        }
    }
    private void validateUser(SysUser user) throws ValidationException {
        BeanValidators.validateWithException(validator, user);
    }
}

@Data
class UserImportResult {
    private final SysUser user;
    private final boolean success;
    private final String error;
    private static int count = 0;
    private final int index;

    private UserImportResult(final SysUser user, final boolean success, final String error) {
        this.user = user;
        this.success = success;
        this.error = error;
        this.index = ++count;
    }

    public static UserImportResult success(final SysUser user) {
        return new UserImportResult(user, true, null);
    }

    public static UserImportResult failure(final SysUser user, final String error) {
        return new UserImportResult(user, false, error);
    }

}
